package com.guldan.jaina.manager;

import com.guldan.core.enums.GAuthResTypeEn;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.search.Pagination;
import com.guldan.core.utils.DateUtil;
import com.guldan.jaina.dto.gauthority.GAuthorityDTO;
import com.guldan.jaina.dto.gauthority.GAuthoritySearchDTO;
import com.guldan.jaina.dto.gauthority.GRoleAuthSaveDTO;
import com.guldan.jaina.dto.grole.GRoleAuthDTO;
import com.guldan.jaina.dto.grole.GRoleDTO;
import com.guldan.jaina.utils.GAuthorityDomainConvertUtils;
import com.guldan.mapper.db.entity.GAuthority;
import com.guldan.mapper.db.entity.GAuthorityExample;
import com.guldan.mapper.db.entity.GRoleAuth;
import com.guldan.mapper.db.entity.GRoleAuthExample;
import com.guldan.mapper.db.mapper.GAuthorityMapperExt;
import com.guldan.mapper.db.mapper.GRoleAuthMapperExt;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2016/11/16
 * Time: 21:11
 */
@Service
public class GAuthorityManager extends BaseManager {

    @Autowired
    private GAuthorityMapperExt gAuthorityMapperExt;

    @Autowired
    private GRoleAuthMapperExt gRoleAuthMapperExt;

    //获取单个权限信息
    public GAuthorityDTO get(Integer id) {
        return GAuthorityDomainConvertUtils.convert(gAuthorityMapperExt.selectByPrimaryKey(id));
    }

    //新增/更新单个权限，传入：GAuthorityDTO
    public GAuthorityDTO save(GAuthorityDTO dto) {

        GAuthority entity;
        if (dto.getId() != null && dto.getId() > 0) {
            entity = gAuthorityMapperExt.selectByPrimaryKey(dto.getId());
            entity.setParent(dto.getParent());
            entity.setName(dto.getName());
            entity.setUrl(dto.getUrl());
            entity.setSysCode(dto.getSysCode());
            entity.setResType(dto.getResType());
            entity.setResources(dto.getResources());
            entity.setSort(dto.getSort());

            entity.setDisabled(dto.getDisabled());
            entity.setModifyTime(DateUtil.getCurrentTime());
            entity.setModifier(dto.getModifier());
            gAuthorityMapperExt.updateByPrimaryKeySelective(entity);
        } else {
            entity = new GAuthority();
            entity.setParent(dto.getParent());
            entity.setName(dto.getName());
            entity.setUrl(dto.getUrl());
            entity.setSysCode(dto.getSysCode());
            entity.setResType(dto.getResType());
            entity.setResources(dto.getResources());
            entity.setSort(dto.getSort());

            entity.setDisabled(dto.getDisabled());
            entity.setCreator(dto.getModifier());
            entity.setCreateTime(DateUtil.getCurrentTime());
            entity.setIsDelete(false);
            gAuthorityMapperExt.insertSelective(entity);
        }
        dto = GAuthorityDomainConvertUtils.convert(entity);
        return dto;
    }

    //删除单个权限信息
    public Boolean delete(Integer id) {
        GAuthority entity = gAuthorityMapperExt.selectByPrimaryKey(id);
        entity.setIsDelete(true);
        return gAuthorityMapperExt.updateByPrimaryKeySelective(entity) > 0;
    }

    //分页查询权限信息列表
    public Pagination<GAuthorityDTO> list(GAuthoritySearchDTO gAuthoritySearchDTO) {
        Pagination<GAuthorityDTO> result = new Pagination<GAuthorityDTO>(gAuthoritySearchDTO.getCurrentPage(), gAuthoritySearchDTO.getPerPage());
        GAuthorityExample example = buildSearchExample(gAuthoritySearchDTO);
        int total = gAuthorityMapperExt.countByExample(example);
        result.setTotalCount(total);
        if (total > 0) {
            List<GAuthorityDTO> data = new ArrayList<GAuthorityDTO>();
            List<GAuthority> list = gAuthorityMapperExt.selectByExampleWithPaging(example, result.getOffset(), result.getPageSize());
            for (GAuthority entity : list) {
                GAuthorityDTO dto = GAuthorityDomainConvertUtils.convert(entity);
                data.add(dto);
            }
            result.setList(data);
        }
        return result;
    }

    //获取所有权限菜单，返回树形结构
    public List<GAuthorityDTO> listAllAuthority() {
        List<GAuthorityDTO> list = getAuthorityListByParentId(0); //先获取根节点菜单
        /*if(list!=null&&list.size()>0){
            for (GAuthorityDTO ga : list){

            }
        }*/
        return list;
    }

    //通过parentId获取菜单权限列表
    public List<GAuthorityDTO> getAuthorityListByParentId(Integer parentId) {
        GAuthorityExample example = new GAuthorityExample();
        GAuthorityExample.Criteria criteria = example.createCriteria();
        criteria.andParentEqualTo(parentId);
        criteria.andResTypeEqualTo(GAuthResTypeEn.MENU.getCode());
        criteria.andDisabledEqualTo(false);
        criteria.andIsDeleteEqualTo(false);
        List<GAuthority> entityList = gAuthorityMapperExt.selectByExample(example);
        List<GAuthorityDTO> dtoList = new ArrayList<>();
        if (entityList != null && entityList.size() > 0) {
            for (GAuthority ga : entityList) {
                GAuthorityDTO gaDto = GAuthorityDomainConvertUtils.convert(ga);
                gaDto.setChildren(getAuthorityListByParentId(gaDto.getId()));
                dtoList.add(gaDto);
            }
        }
        return dtoList;
    }

    //通过角色id获取菜单权限列表，树形结构
    public List<GAuthorityDTO> getAuthorityListByRoleId(Integer roleId) {
        //先查询角色所授权的权限菜单记录
        GRoleAuthExample example = new GRoleAuthExample();
        GRoleAuthExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andIsDeleteEqualTo(false);
        criteria.andDisabledEqualTo(false);
        List<GAuthorityDTO> list = new ArrayList<>();
        //查出所有的权限id列表
        List<GRoleAuth> gRoleAuthList = gRoleAuthMapperExt.selectByExample(example);
        List<GAuthorityDTO> result = new ArrayList<>();
        if (gRoleAuthList != null && gRoleAuthList.size() > 0) {
            GAuthorityExample gAuthorityExample = new GAuthorityExample();
            GAuthorityExample.Criteria gAuthorityCriteria = gAuthorityExample.createCriteria();
            List<Integer> ids = new ArrayList<>();
            for (GRoleAuth gRoleAuth : gRoleAuthList) {
                ids.add(gRoleAuth.getAuthId());
            }
            gAuthorityCriteria.andIdIn(ids);
            gAuthorityCriteria.andIsDeleteEqualTo(false);
            gAuthorityCriteria.andDisabledEqualTo(false);

            List<GAuthority> gAuthorityList = gAuthorityMapperExt.selectByExample(gAuthorityExample);
            List<GAuthorityDTO> all = new ArrayList<>();

            if (gAuthorityList != null && gAuthorityList.size() > 0) {
                for (GAuthority ga : gAuthorityList) {
                    all.add(GAuthorityDomainConvertUtils.convert(ga));
                }


                logger.info("json1:" + JSONArray.fromObject(all).toString());

                result = getAuthorityListByRoleId(all, 0);

                logger.info("json2:" + JSONArray.fromObject(result).toString());
            }
        }
        return result;
    }

    private List<GAuthorityDTO> getAuthorityListByRoleId(List<GAuthorityDTO> list, Integer parentId) {
        List<GAuthorityDTO> dtoList = new ArrayList<>();
        for (GAuthorityDTO ga : list) {
            if (ga.getParent().equals(parentId)) {
                ga.setChildren(getAuthorityListByRoleId(list, ga.getId()));
                dtoList.add(ga);
            }
        }
        return dtoList;
    }

    //修改某个角色用户的权限列表
    public List<GAuthorityDTO> saveAuthByRoleId(GRoleAuthSaveDTO dto) {
        List<GAuthorityDTO> list = new ArrayList<>();
        if (dto != null && dto.getAuthIds() != null && dto.getAuthIds().size() > 0) {
            //先删除所有的记录，再进行添加
            GRoleAuthExample example = new GRoleAuthExample();
            GRoleAuthExample.Criteria criteria = example.createCriteria();
            criteria.andRoleIdEqualTo(dto.getRoleId());
            gRoleAuthMapperExt.deleteByExample(example);

            //删除后进行逐个添加
            for (Integer authId : dto.getAuthIds()) {
                GRoleAuth gRoleAuth = new GRoleAuth();
                gRoleAuth.setRoleId(dto.getRoleId());
                gRoleAuth.setAuthId(authId);
                gRoleAuth.setDisabled(false);
                gRoleAuth.setIsDelete(false);
                gRoleAuth.setCreateTime(DateUtil.getCurrentTime());

                gRoleAuthMapperExt.insertSelective(gRoleAuth);
            }
        }
        return getAuthorityListByRoleId(dto.getRoleId());
    }

    //build查询Example
    private GAuthorityExample buildSearchExample(GAuthoritySearchDTO search) {
        GAuthorityExample example = new GAuthorityExample();
        GAuthorityExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(search.getName())) {
            criteria.andNameEqualTo(search.getName());
        }
        if (search.getParent() != null && search.getParent() > 0) {
            criteria.andParentEqualTo(search.getParent());
        }
        if (search.getId() != null && search.getId() > 0) {
            criteria.andIdEqualTo(search.getId());
        }
        criteria.andIsDeleteEqualTo(Boolean.FALSE);
        if (StringUtils.isNotBlank(search.getOrderByClause())) {
            example.setOrderByClause(search.getOrderByClause());
        } else {
            example.setOrderByClause("id asc");
        }
        return example;
    }


}
